<!--
  @author:  long
  @date:    2023/3/2
  @file:    供应商管理
  @require:
-->
<template>
  <div class="supplierList app-container">
    <!-- 供应商列表主体 start -->
    <div class="px-2">
      <!-- 搜索 start -->
      <avue-form
        :option="queryFormOption"
        v-model="queryForm"
        ref="queryFormRef"
      >
        <!--   供应商状态   -->
        <template #status>
          <el-select
            clearable
            v-model="queryForm.status"
            placeholder="供应商状态"
          >
            <el-option
              v-for="(dict, index) in supplier_status"
              :label="dict.label"
              :value="dict.value"
              :key="index"
            ></el-option>
          </el-select>
        </template>
        <!-- 供应商星级 -->
        <template #starRating>
          <el-select
            clearable
            v-model="queryForm.starRating"
            placeholder="信用星级"
          >
            <el-option
              v-for="(dict, index) in customer_star"
              :label="dict.label"
              :value="dict.value"
              :key="index"
            ></el-option>
          </el-select>
        </template>
        <!--    更新时间    -->
        <template #updateTime>
          <el-date-picker
            style="width: 100%"
            v-model="updateTime"
            type="daterange"
            start-placeholder="更新时间起"
            end-placeholder="更新时间止"
            format="YYYY-MM-DD"
            valueFormat="YYYY-MM-DD"
          />
        </template>
        <template #menu-form="{}">
          <el-button icon="Search" type="primary" @click="handleSubmit"
            >查询</el-button
          >
          <el-button icon="RefreshLeft" @click="handleEmpty">重置</el-button>
          <el-button icon="Filter" link type="primary" @click="openDrawer"
            >高级筛选</el-button
          >
        </template>
      </avue-form>
      <!-- 搜索 end -->

      <!-- 操作按钮 start-->
      <div class="px-2 pb-3">
        <el-button type="primary" icon="Plus" @click="addSupplierList">
          新建供应商
        </el-button>
        <el-button icon="Refresh" type="primary" plain>转成客户</el-button>
        <el-button icon="Download" type="primary" plain>导入数据</el-button>
        <el-button icon="Upload" type="primary" plain>导出数据</el-button>
        <el-button icon="EditPen" type="primary" plain @click="toUpdate"
          >编辑供应商</el-button
        >
        <el-button icon="Delete" type="primary" plain @click="deleteSupplier"
          >删除供应商</el-button
        >
      </div>
      <!-- 操作按钮 end-->

      <!--   供应商列表显示start   -->
      <el-table
        ref="tableRef"
        :data="tableData"
        v-loading="loading"
        style="width: 100%"
        border
        @selection-change="handleSelectionChange"
        @row-dblclick="goDetails"
      >
        <el-table-column align="center" type="selection" width="55" />
        <el-table-column
          prop="supplierNumber"
          label="编号"
          align="center"
        ></el-table-column>
        <el-table-column label="供应商名称" prop="supplierName">
          <!-- <template #default="scope">
            <el-button link type="primary" @click="goDetails(scope.row)">{{
              scope.row.supplierName
            }}</el-button>
          </template> -->
        </el-table-column>
        <el-table-column label="供应商状态" align="center">
          <template #default="scope">
            <dict-tag :options="supplier_status" :value="scope.row.status" />
          </template>
        </el-table-column>
        <el-table-column label="供应商星级" align="center">
          <template #default="scope">
            <dict-tag :options="customer_star" :value="scope.row.starRating" />
          </template>
        </el-table-column>
        <!--        <el-table-column label="联系人"></el-table-column>-->
        <!--        <el-table-column-->
        <!--          label="联系电话"-->
        <!--          prop="mainContactPhone"-->
        <!--        ></el-table-column>-->
        <el-table-column
          label="创建时间"
          prop="createTime"
          align="center"
        ></el-table-column>
      </el-table>
      <pagination
        v-show="total > 0"
        :total="total"
        v-model:page="queryForm.pageNum"
        v-model:limit="queryForm.pageSize"
        @pagination="getList"
      />
      <!--   供应商列表显示end   -->

      <!-- 高级筛选 start -->
      <el-drawer class="p-0" size="50%" v-model="drawer" title="高级筛选">
        <avue-form
          :option="drawerFormOption"
          v-model="queryForm"
          ref="drawerFormRef"
        >
          <template #menu-form="{}">
            <el-button icon="Search" type="primary" @click="handleSubmit"
              >查询</el-button
            >
            <el-button icon="RefreshLeft" @click="handleDrawerFormEmpty"
              >重置</el-button
            >
          </template>
          <!--   供应商状态   -->
          <template #status>
            <el-select
              v-model="queryForm.status"
              placeholder="供应商状态"
              class="w-full"
            >
              <el-option
                v-for="(dict, index) in supplier_status"
                :label="dict.label"
                :value="dict.value"
                :key="index"
              ></el-option>
            </el-select>
          </template>
          <!-- 行业类型 -->
          <template #industryTypeCode>
            <el-select
              v-model="queryForm.industryTypeCode"
              placeholder="行业类别"
              class="w-full"
            >
              <el-option
                v-for="(dict, index) in industry_category"
                :key="index"
                :value="dict.value"
                :label="dict.label"
              ></el-option>
            </el-select>
          </template>

          <!-- 信用星级 -->
          <template #starRating>
            <el-select
              v-model="queryForm.starRating"
              placeholder="信用星级"
              class="w-full"
            >
              <el-option
                v-for="(dict, index) in customer_star"
                :label="dict.label"
                :value="dict.value"
                :key="index"
              ></el-option>
            </el-select>
          </template>

          <!-- 归属公司 -->
          <template #orgId>
            <el-tree-select
              style="width: 100%"
              v-model="queryForm.orgId"
              :data="companyOptions"
              :props="{
                value: 'id',
                label: 'label',
                children: 'children'
              }"
              placeholder="请选择归属公司"
              value-key="id"
              filterable
            />
          </template>
        </avue-form>
      </el-drawer>
      <!-- 高级筛选 end -->
    </div>
    <!-- 供应商列表主体end -->
    <!--  公共弹窗start -->
    <el-dialog
      v-model="dialogObj.visible"
      destroy-on-close
      :close-on-click-modal="false"
      :width="dialogObj.width"
      :title="dialogObj.title"
    >
      <!--   底部按钮   -->
      <template #footer>
        <el-button @click="handleCloseDialog">取消</el-button>
        <el-button type="primary">保存</el-button>
      </template>
    </el-dialog>
    <!--  公共弹窗end -->
  </div>
</template>

<script setup name="SupplierList">
import useCommonStore from '@/store/modules/common'
import { getCurrentInstance, toRaw } from 'vue'
import { useRouter } from 'vue-router'
import { delSupplier, getSupplierList } from '@/api/sourceModules/supplier'
import useUserStore from '@/store/modules/user'
const router = useRouter()
const userStore = useUserStore()
// 通用数据store
const commonStore = useCommonStore()
const { proxy } = getCurrentInstance()
const drawer = ref(false) //抽屉弹窗
const companyOptions = ref([])
const loading = ref(false)
const data = reactive({
  queryForm: {
    pageNum: 1,
    pageSize: 10
  },
  total: 0,
  tableData: [],
  updateTime: [], //更新时间
  // 查询的form表单配置
  queryFormOption: {
    labelWidth: 0,
    menuSpan: 6,
    submitBtn: false,
    emptyBtn: false,
    column: [
      {
        prop: 'supplierName',
        placeholder: '供应商名称',
        span: 4
      },
      // {
      //   prop: 'mainContactPhone',
      //   placeholder: '联系人电话',
      //   span: 3
      // },
      {
        prop: 'status', //状态
        span: 3
      },
      {
        prop: 'starRating', //星级
        span: 3
      },
      {
        prop: 'updateTime',
        span: 5
      }
    ]
  },
  //   高级筛选弹窗form表单配置
  drawerFormOption: {
    labelWidth: 100,
    submitBtn: false,
    emptyBtn: false,
    column: [
      {
        label: '供应商名称',
        prop: 'supplierName',
        placeholder: '供应商名称',
        span: 12
      },
      {
        label: '供应商税号',
        prop: 'supplierTaxcode',
        placeholder: '供应商税号',
        span: 12
      },
      {
        label: '供应商状态',
        prop: 'status',
        span: 12
      },
      {
        label: '行业类型',
        prop: 'industryTypeCode',
        placeholder: '行业类型',
        span: 12
      },

      {
        label: '供应商星级',
        prop: 'starRating',
        placeholder: '供应商星级',
        span: 12
      },
      {
        label: '归属公司',
        prop: 'orgId',
        placeholder: '归属公司',
        span: 12
      }
      // {
      //   label: '联系人姓名',
      //   prop: 'mainContactName',
      //   placeholder: '联系人姓名',
      //   span: 12
      // },
      // {
      //   label: '联系人电话',
      //   prop: 'mainContactPhone',
      //   placeholder: '联系人电话',
      //   span: 12
      // }
    ]
  },
  dialogObj: {
    visible: false,
    title: '',
    width: '50%',
    model: '',
    type: {}
  },
  selectionData: []
})

const {
  updateTime,
  queryForm,
  tableData,
  queryFormOption,
  drawerFormOption,
  dialogObj,
  total,
  selectionData
} = toRefs(data)
const {
  supplier_status,
  supplier_class,
  customer_source,
  customer_star,
  industry_category,
  contacts_role
} = proxy.useDict(
  'supplier_status',
  'supplier_class',
  'customer_source',
  'customer_star',
  'industry_category',
  'contacts_role'
)

/**
 * 跳转详情
 * @param row 行数据
 */
function goDetails(row) {
  router.push({
    path: '/source/sourceModules/supplierDetails',
    query: { supplierId: row.id }
  })
}

/**
 * 弹窗关闭
 */
function handleCloseDialog() {
  dialogObj.value.visible = false
}

/**
 * 弹窗开启操作
 * @param type 弹窗组件类型
 *
 */
function handleOpenDialog(type) {
  dialogObj.value.title = dialogObj.value.type[type].title
  dialogObj.value.width = dialogObj.value.type[type].width
  dialogObj.value.model = type
  dialogObj.value.visible = true
}

/**
 * 表格多选
 */
function handleSelectionChange(val) {
  selectionData.value = val
  console.info('selectionData', selectionData)
}

function toUpdate() {
  if (!selectionData.value.length) {
    proxy.$modal.msgWarning('请选择要编辑的数据')
    return
  }
  if (selectionData.value.length > 1) {
    proxy.$modal.msgWarning('只能编辑一条数据')
    return
  }
  router.push({
    path: '/source/sourceModules/addSupplier',
    query: { flag: 'update', supplierId: selectionData.value[0].id }
  })
}

/**
 * 新建供应商
 */
function addSupplierList() {
  router.push({
    path: '/source/sourceModules/addSupplier',
    query: { flag: 'add' }
  })
}

/**
 * 删除供应商
 */
function deleteSupplier() {
  if (!selectionData.value.length) {
    proxy.$modal.msgWarning('请选择要删除的数据')
    return
  }
  proxy.$modal
    .confirm('是否确认删除选中的客户数据-？')
    .then(res => {
      let ids = selectionData.value
        .map(item => {
          return item.id
        })
        .join(',')
      console.info('ids', ids)
      const params = {
        ids
      }
      delSupplier(params).then(res => {
        proxy.$modal.msgSuccess(res.msg)
        getList()
      })
    })
    .catch(() => {})
}

/**
 * 打开高级筛选抽屉
 */
function openDrawer() {
  drawer.value = true
}

/**
 * 查询
 */
function handleSubmit() {
  queryForm.value.pageNum = 1
  getList()
}

function getList() {
  loading.value = true
  let params = JSON.parse(JSON.stringify(queryForm.value))
  if (updateTime.value != null && updateTime.value.length > 0) {
    params.updateTimeStart = updateTime.value[0] + ' 00:00:00'
    params.updateTimeEnd = updateTime.value[1] + ' 23:59:59'
  } else {
    params.updateTimeStart = undefined
    params.updateTimeEnd = undefined
  }
  delete params.updateTime
  if (userStore.user.orgId != 484) {
    params.orgId = userStore.user.orgId
  }
  getSupplierList(params)
    .then(res => {
      if (res.data != null) {
        tableData.value = res.data.records
        total.value = res.data.total
      } else {
        tableData.value = []
        total.value = 0
      }
    })
    .finally(() => {
      loading.value = false
    })
}

/**
 * 重置
 */
async function handleEmpty() {
  updateTime.value = []
  proxy.$refs.queryFormRef.resetFields()

  queryForm.value = {
    pageNum: 1,
    pageSize: 10
  }
  await getList()
}

/**
 * 高级筛选清空
 * @returns {Promise<void>}
 */
async function handleDrawerFormEmpty() {
  updateTime.value = []
  proxy.$refs.drawerFormRef.resetFields()
  queryForm.value = {
    pageNum: 1,
    pageSize: 10
  }
  await getList()
}
/**
 * 初始化
 */
async function init() {
  // 获取归属公司数据
  await commonStore.getCompanyData().then(data => {
    companyOptions.value = data
  })
  getList()
}
init()
</script>

<style scoped lang="scss">
.customerList {
  .el-drawer .avue-form {
    @apply p-0;
  }
}
</style>
